package com.slkj.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.slkj.dto.Result;
import com.slkj.dto.SpecialTaskDTO;
import com.slkj.dto.StatusCode;
import com.slkj.entity.CountiesDuty;
import com.slkj.entity.CountiesTask;
import com.slkj.entity.File;
import com.slkj.mapper.CountiesDutyMapper;
import com.slkj.service.CountiesService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName CountiesController.java
 * @Description TODO
 * @createTime 2020年03月20日 09:58:00
 */
@CrossOrigin
@Transactional
@RestController
@RequestMapping("${address.prefix}/counties")
public class CountiesController {
    private Logger log = LoggerFactory.getLogger(SpecialController.class);

    @Autowired
    private CountiesService countiesService;
    @Autowired
    private CountiesDutyMapper countiesDutyMapper;


    @PostMapping("/createTask")
    public Result createTask(@RequestBody CountiesTask countiesTask) {

        log.info("----------------------->>>createTask(@RequestBody CountiesTask countiesTask) ");
        if (countiesTask == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        countiesService.createTask(countiesTask, username);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/taskUpload")
    public Result taskUpload(@RequestBody String data) throws SQLException {
        log.info("----------------------->>>taskUpload(@RequestParam(value = \"file\") MultipartFile multipartFile)");

        JSONObject jsonObject = JSONObject.parseObject(data);
        List<File> fileList = JSONObject.parseArray(jsonObject.getString("file"), File.class);
        System.out.println(fileList.toString());
        String dutyId = jsonObject.getString("dutyId");
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        log.info("----------------------->>>获取参数dutyId=" + dutyId);
        CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
        if (countiesDuty != null) {
            if (countiesDuty.getCountiesAuditStatus().equals("已完成") || countiesDuty.getCountiesAuditStatus().equals("未完成")) {
                return new Result(false, StatusCode.ERROR, "该任务已结束");
            }
            if (!countiesDuty.getCountiesAuditStatus().equals("驳回") && !countiesDuty.getCountiesAuditStatus().equals("待上传")) {
                return new Result(false, StatusCode.ERROR, "不符合上传文件规定");
            }
        }

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }


        countiesService.taskUpload(fileList, dutyId, variables, count);

        return new Result(true, StatusCode.OK, "success");
    }


    @PostMapping("/passTask")
    public Result passTask(@RequestBody String data) throws SQLException {
        log.info("----------------------->>>passTask(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);
        if (StringUtils.isBlank(count) || variables == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        if (!StringUtils.isNumeric(count)) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty != null) {
                if (countiesDuty.getCountiesPerAudit().equals("通过") || countiesDuty.getCountiesPerAudit().equals("未完成")) {
                    return new Result(false, StatusCode.ERROR, "该任务已结束");
                }
                if (countiesDuty.getCountiesPerAudit().equals("驳回")) {
                    return new Result(false, StatusCode.ERROR, "不能审核该任务");
                }
            }
        }


//        boolean statusCheck = statusCheck(variables);
//        if (!statusCheck) {
//            return new Result(false, StatusCode.ERROR, "参数异常");
//        }


        countiesService.passTask(dutyIdList, variables, count);

        return new Result(true, StatusCode.OK, "success");
    }

    ////

    @PostMapping("/noPassTask")
    public Result noPassTask(@RequestBody String data) throws SQLException {
        log.info("----------------------->>>noPassTask(@RequestBody String data) ");

        JSONObject jsonObject = JSONObject.parseObject(data);
        String count = jsonObject.getString("count");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);
        if (StringUtils.isBlank(count) || variables == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        if (!StringUtils.isNumeric(count)) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

//        boolean statusCheck = statusCheck(variables);
//        if (!statusCheck) {
//            return new Result(false, StatusCode.ERROR, "参数异常");
//        }
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty != null) {
                if (countiesDuty.getCountiesPerAudit().equals("通过") || countiesDuty.getCountiesPerAudit().equals("未完成")) {
                    return new Result(false, StatusCode.ERROR, "该任务已结束");
                }
                if (countiesDuty.getCountiesPerAudit().equals("驳回")) {
                    return new Result(false, StatusCode.ERROR, "不能审核该任务");
                }
            }
        }


        countiesService.noPassTask(dutyIdList, variables, count);

        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/getTaskFeedback")
    public Result getTaskFeedback(@RequestBody String data) {
        JSONObject jsonObject = JSONObject.parseObject(data);
        String title = jsonObject.getString("title");
        String light = jsonObject.getString("light");
        String checkUnitUserId = jsonObject.getString("checkUnitUserId");
        String toCheckUnitUserId = jsonObject.getString("toCheckUnitUserId");
        String status = jsonObject.getString("status");

        if (StringUtils.isNotBlank(status)) {
            status = "已完成";
        }


        List<String> projectTime = new ArrayList<>();


        Date beginDate = null;
        Date endDate = null;

        if (StringUtils.isNotBlank(jsonObject.getString("projectTime"))) {
            projectTime = JSONObject.parseArray(jsonObject.getString("projectTime"), String.class);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            try {
                beginDate = simpleDateFormat.parse(projectTime.get(0));
                endDate = simpleDateFormat.parse(projectTime.get(1));
            } catch (ParseException e) {
                return new Result(false, StatusCode.ERROR, "日期格式转换异常");
            }
        } else if (StringUtils.isNotBlank(jsonObject.getString("month"))) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            try {
                beginDate = simpleDateFormat.parse(jsonObject.getString("month") + "/01");
                endDate = simpleDateFormat.parse(jsonObject.getString("month") + "/31");
            } catch (ParseException e) {
                return new Result(false, StatusCode.ERROR, "日期格式转换异常");
            }

        }
        String gotoPageString = jsonObject.getString("page");
        String pageSizeString = jsonObject.getString("pageSize");

        log.info("---------------------------------------------->>>>>>>>获取title=" + title);
        log.info("---------------------------------------------->>>>>>>>获取beginDate=" + beginDate + toString());
        log.info("---------------------------------------------->>>>>>>>获取light=" + light);
        log.info("---------------------------------------------->>>>>>>>获取endDate=" + endDate + toString());
        log.info("---------------------------------------------->>>>>>>>获取gotoPageString=" + gotoPageString);
        log.info("---------------------------------------------->>>>>>>>获取pageSizeString=" + pageSizeString);


        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        int gotoPage = 1;

        if (StringUtils.isNotBlank(gotoPageString) && StringUtils.isNumeric(gotoPageString)) {
            gotoPage = Integer.parseInt(gotoPageString);
        }

        int pageSize = 10;

        if (StringUtils.isNotBlank(pageSizeString) && StringUtils.isNumeric(pageSizeString)) {
            pageSize = Integer.parseInt(pageSizeString);
        }


        PageInfo<SpecialTaskDTO> pageInfo = countiesService.getTaskFeedback(title, beginDate, endDate, light, username, gotoPage, pageSize, checkUnitUserId, toCheckUnitUserId, status);


        if (pageInfo == null) {
            log.error("查询绩效县区反馈,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }

        if (pageInfo.getSize() == 0) {
            log.error("查询绩效县区反馈,无数据");
            return new Result(true, StatusCode.NULL, "无数据");
        }
        return new Result(true, StatusCode.OK, "查询成功", pageInfo);
    }

    @PostMapping("/audit")
    public Result audit(@RequestBody String data) throws SQLException {

        log.info("----------------------->>> audit(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        String count = jsonObject.getString("count");
        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);

        String score = jsonObject.getString("score");
        String completeCase = jsonObject.getString("completeCase");
        String auditIdea = jsonObject.getString("auditIdea");

        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);

        if (dutyIdList == null || StringUtils.isBlank(score) || StringUtils.isBlank(completeCase) || StringUtils.isBlank(auditIdea) || StringUtils.isBlank(count) || variables == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }
        if (!StringUtils.isNumeric(score) || !StringUtils.isNumeric(count)) {
            return new Result(false, StatusCode.ERROR, "参数异常");
        }

        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }
        for (String dutyId : dutyIdList) {
            CountiesDuty countiesDuty = countiesDutyMapper.selectByDutyId(dutyId);
            if (countiesDuty != null) {
                if (countiesDuty.getCountiesPerAudit().equals("通过") || countiesDuty.getCountiesPerAudit().equals("未完成")) {
                    return new Result(false, StatusCode.ERROR, "该任务已结束");
                }
                if (countiesDuty.getCountiesPerAudit().equals("驳回")) {
                    return new Result(false, StatusCode.ERROR, "不能审核该任务");
                }
            }

        }

        countiesService.audit(variables, count, dutyIdList, score, completeCase, auditIdea);
        return new Result(true, StatusCode.OK, "success");
    }

    @PostMapping("/lightAdjust")
    public Result lightAdjust(@RequestBody String data) throws SQLException {
        log.info("----------------------->>>lightAdjust(@RequestBody String data)");

        JSONObject jsonObject = JSONObject.parseObject(data);

        String username = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
        List<Map> variables = JSONObject.parseArray(jsonObject.getString("variables"), Map.class);


        if (variables == null) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }


        if (StringUtils.isBlank(username) || username.equals("null")) {
            return new Result(false, StatusCode.LOGINDISABLED, "登录失效,请重新登录");
        }

        List<String> dutyIdList = JSONObject.parseArray(jsonObject.getString("dutyId"), String.class);

        String light = jsonObject.getString("light");
        String lightCause = jsonObject.getString("lightCause");


        log.info("----------------------->>>获取参数light=" + light);
        if (dutyIdList == null || StringUtils.isBlank(light) || StringUtils.isBlank(lightCause)) {
            return new Result(false, StatusCode.ERROR, "参数为空");
        }

        countiesService.lightAdjust(dutyIdList, light, variables, lightCause);

        return new Result(true, StatusCode.OK, "success");
    }


}
